//
//  OrdersViewController.m
//  Restaurant
//
//  Created by wanghuan on 15/4/24.
//  Copyright (c)  年 wanghuan. All rights reserved.
//

#import "OrdersViewController.h"

@interface OrdersViewController () {

    UIButton *btn;
    
    UILabel *commentLabel;
    
    

}

@end

@implementation OrdersViewController

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    
    IsViewState = YES;
    
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"tabbarSelect" object:nil];

}



- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib
    
    self.view.backgroundColor = AppBackGroundColor;
    
    self.remark = @"";
    self.payType = @"";
    self.merchantId = @"aaaa";
    
    _shopArray = [[NSMutableArray alloc]init];
    
    _OrderArr = [[NSMutableArray alloc]init];
    
    _MyTableView  = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, APPWith, APPHeight-64) style:UITableViewStyleGrouped];
    
    _MyTableView.delegate = self;
    _MyTableView.dataSource = self;
    _MyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
     [self.view addSubview:_MyTableView];
    

    int sum = 0;
    
    [_shopArray addObjectsFromArray:self.shopMutArray];
    
    for (int i = 0; i < _shopArray.count; i++) {
        shoppingModel *model = [_shopArray objectAtIndex:i];
        sum += [model.number intValue];
    }

    shoppingModel *model = [[shoppingModel alloc]init];
    
    model.nameStr = @"总计";
    
    model.prices = self.price;
    
    if (sum == 0) {
        model.prices = @"0";
    }
    
    model.number = [NSString stringWithFormat:@"%d",sum];
    
    [_shopArray addObject:model];
    
    _payStyleArr = @[@"支付宝支付",@"微信支付",@"现金支付"];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    if (section == 0) {
        return _shopArray.count;
    }
    
    if (section == 1) {
        return 1;
    }
    
    if (section == 3) {
        return 1;
    }
    
    return _payStyleArr.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

   
    
    if (indexPath.section == 0) {
        return 40;
    }
    
    return 50;
    

}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

    return 2;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 3) {
        return 75;
    }

    return 2;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    
    return 4;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        OrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"order"];
        
        
        if (!cell) {
            cell = [[NSBundle mainBundle]loadNibNamed:@"OrderTableViewCell" owner:self options:nil].lastObject;
        }
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(15, 40-1, APPWith-10, 1)];
        
        view.backgroundColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1];
        [cell.contentView addSubview:view];
        
        shoppingModel *model = [_shopArray objectAtIndex:indexPath.row];
        
        cell.nameLabel.text = model.nameStr;
        cell.numberLabel.text = [NSString stringWithFormat:@"X%@",model.number];
        cell.priceLabel.text =  [NSString stringWithFormat:@"￥%@",model.prices];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    }
    
    if (indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        }
        
        cell.textLabel.text = @"添加备注";
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        if (!commentLabel) {
            
            commentLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, (50-20)/2, cell.frame.size.width-100, 20)];
            commentLabel.textColor = [UIColor grayColor];
            
            commentLabel.font = [UIFont systemFontOfSize:11];
            
            [cell.contentView addSubview:commentLabel];
        }
        commentLabel.text = @"";
        commentLabel.text = self.remark;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    if (indexPath.section == 3) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"button"];
//        tableView.separatorStyle = NO;
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"button"];
        }
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, cell.bounds.size.width);
        
        cell.backgroundColor = [UIColor clearColor];
        btn = [[UIButton alloc]initWithFrame:CGRectMake(10, 0, APPWith-20, 50)];
        
        [btn setBackgroundImage:[UIImage imageNamed:@"button1.png"] forState:UIControlStateNormal];
        
//        btn.frame = CGRectMake(10, tableView.contentSize.height+75, APPWith-20, 50);
        [btn setTitle:@"立即下单" forState:UIControlStateNormal];
        
        [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        
        [cell.contentView addSubview:btn];
        
        return cell;
        
    }
    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"qqq"];
    
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"qqq"];
    }
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(15, 50-1, APPWith-10, 1)];
    
    view.backgroundColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:244.0/255.0 alpha:1];
    
    [cell.contentView addSubview:view];

    
    cell.textLabel.text = [_payStyleArr objectAtIndex:indexPath.row];
    
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
    

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    
    
    if (cellIndexPath.section != indexPath.section) {
        
        UITableViewCell *Paycell = [tableView cellForRowAtIndexPath:cellIndexPath];
        
        Paycell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    if (indexPath.section == 2) {
        
        cellIndexPath = indexPath;
        
        self.payType = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    
    if (indexPath.section == 1) {
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        CommentsViewController *cvc = [[CommentsViewController alloc]init];
        
        cvc.commentDemend = self.commentDemend;
        cvc.commentArr = self.commentArr;
        if ([self.remark length]) {
            cvc.commmentStr = [NSMutableString stringWithString:self.remark];
        }
        
        cvc.Comment = ^(NSString *commentStr,NSString *commentDemend,NSMutableArray *commentArr) {
        
            self.remark = commentStr;
            self.commentDemend = commentDemend;
            self.commentArr = commentArr;
            [_MyTableView reloadData];
        
        };
        
        [self.navigationController pushViewController:cvc animated:YES];
    }
    
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 2) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
    }


}

#pragma mark - 立即下单(还没商家id)

- (void)btnClick {

    _manager = [[AFHTTPRequestOperationManager alloc]init];
    
    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/json",@"application/json", nil];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    self.userId = [user objectForKey:NSLocalizedString(usersId, nil)];
    
    if (!self.userId) {
        
        LoginViewController *lvc = [[LoginViewController alloc]init];
        
        //指定跳转页面
        lvc.viewController = self;
        
        [self.navigationController pushViewController:lvc animated:YES];
        
        return;
    }
    
    
    for (int i = 0; i < self.shopMutArray.count; i++) {
        
        shoppingModel *model = [self.shopMutArray objectAtIndex:i];
     
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[model.nameStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],@"title",model.productId,@"productId",model.prices,@"perPrice",model.number,@"num", nil];
        
        [self.OrderArr addObject:dict];
    }
    
    //接收MerchantId
    NSString *MerchantId = [SavaMerchantId ShareMerchantId].merchantId;
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[self.remark stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],@"remark",self.payType,@"payType",MerchantId,@"merchantId",self.price,@"totalPrice",self.userId,@"userId",self.OrderArr,@"productList", nil];
   
    NSLog(@"%@",dict);
    
    
    if (!self.payType.length) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"请选择支付类型", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil, nil];
        
        [alertView show];
        
        return;
        
        
    }
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, APPWith, APPHeight)];
    
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    
    //创建一个活动指示器，一般情况下都是用在联网等待的
    UIActivityIndicatorView *active = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    //自带大小一般直接设置位置到屏幕的中间
    active.frame = CGRectMake(APPWith/2-10,(APPHeight-64)/2-20, 20, 20);
    
    //菊花的颜色
    active.color = [UIColor grayColor];
    
    //开始旋转
    [active startAnimating];
    
    [view addSubview:active];
    
    
    [self.view addSubview:view];
    
   
    NSDictionary *params = [NSDictionary dictionaryWithObject:[self DataTOjsonString:dict]forKey:@"params"] ;
    
    NSLog(@"%@",params);
    
    
    
    [_manager POST:OrdersUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"responseObject = %@",[NSDictionary dictionaryWithObject:dict forKey:@"params"]);
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"支付成功", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil, nil];
        
        [alertView show];
        
        //停止旋转
        [active stopAnimating];
        
        view.hidden = YES;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@" - - - - - - error = %@",error);

            
        if (IsViewState) {
            
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"支付失败,请重新支付", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil, nil];
            
            alertView.tag = 1;
            
            [alertView show];
        }
      
        
        view.hidden = YES;
        [active stopAnimating];
    }];

}

#pragma mark - 字典转json
-(NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    NSArray *array = self.navigationController.viewControllers;
   
    if (!buttonIndex) {
        
        [self.navigationController popToViewController:array[2] animated:YES];
        
        
    }
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"BackFromOrdersViewController" object:nil];

}

- (void)viewWillDisappear:(BOOL)animated {

    if(_manager) {
    
        [_manager.operationQueue cancelAllOperations];
        
        IsViewState = NO;
    
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)backClick:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}
@end
